package org.example.chat.websocket.messagehandler;

import cn.hutool.json.JSONUtil;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.example.chat.websocket.entity.MessagePack;
import org.example.chat.websocket.entity.ChannelContext;
import org.example.chat.entity.ChatMessage;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 聊天消息处理器
 * @author cheval
 */
@Component
public class ChatMessageHandler implements MessageHandler {

    @Override
    public void handler(MessageHandlerContext messageHandlerContext) {
        // 1. 将消息存入数据库，消息初始为未签收状态
        MessagePack messagePack = messageHandlerContext.messagePack;
        ChatMessage chatMessage = messagePack.getChatMessage();
        // 设置id 用户id + 用户id + 时间
        String messageId = chatMessage.getSendUserId() + chatMessage.getReceiveUserId() + System.currentTimeMillis();
        chatMessage.setId(messageId);
        // 设置未签收
        chatMessage.setSignFlag(0);
        // 设置聊天时间
        chatMessage.setCreateTime(LocalDateTime.now());
        // 2. 消息转发
        // 获取转发用户的channel
        Channel channel = ChannelContext.getChannel(chatMessage.getReceiveUserId());
        if (channel == null) {
            // 转发用户不在线

        } else {
            // 用户处于在线状态
            channel.writeAndFlush(new TextWebSocketFrame(JSONUtil.toJsonStr(messagePack)));
        }
    }
}
